package com.wise.site.main;

import java.util.List;

import org.taptwo.android.widget.CircleFlowIndicator;
import org.taptwo.android.widget.ViewFlow;
import org.taptwo.android.widget.ViewFlow.OnScrollListener;
import org.taptwo.android.widget.ViewFlow.ViewSwitchListener;

import com.wise.site.R;
import com.wise.site.WiseSiteApplication;
import com.wise.site.adapter.AdvListAdapter;
import com.wise.site.adapter.ArrayListAdapter;
import com.wise.site.adapter.IndexerBarAdapter;
import com.wise.site.adapter.InfoListAdatper;
import com.wise.site.adapter.InfoListAdatper.ITEM_TYPE;
import com.wise.site.detail.InfoDetailsActivity;
import com.wise.site.detail.ShopsDetailsActivity;
import com.wise.site.protocol.action.BannerAction;
import com.wise.site.protocol.action.InfoListAction;
import com.wise.site.protocol.base.ProtocolManager;
import com.wise.site.protocol.base.SoapAction.ACTION_TYPE;
import com.wise.site.protocol.base.SoapAction.ActionListener;
import com.wise.site.protocol.result.Adv;
import com.wise.site.protocol.result.AdvResult;
import com.wise.site.protocol.result.AdvSuperResult;
import com.wise.site.protocol.result.IndexerBarEntry;
import com.wise.site.protocol.result.InfoItem;
import com.wise.site.protocol.result.InfoItemsResult;
import com.wise.site.protocol.result.ModelResult;
import com.wise.site.protocol.result.ShopItem;
import com.wise.site.protocol.result.ShutcutEntry;
import com.wise.site.protocol.result.TabItem;
import com.wise.site.utils.Constanct;
import com.wise.site.utils.CycledThread;
import com.wise.site.utils.FileCache;
import com.wise.site.utils.ImageLoader;
import com.wise.site.utils.ImageLoader.Imager;
import com.wise.site.utils.Log;
import com.wise.site.widget.AdvView;
import com.wise.site.widget.HeadlineScrollView;
import com.wise.site.widget.IndexerBarGallery;

import android.app.Activity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 首页activity
 * @author huangyue
 *
 * 2012-9-18
 */
public class IndexerActivity extends Activity implements OnClickListener{
	private ViewFlow adViewFlow;
	private ViewFlow shopViewFlow;
	private AdvListAdapter mAdvAdapter;
	private View smallAd;
	private ListView headlineList;
	private InfoListAdatper headline;
	private InfoListAdatper headlineShop;
	private IndexerBarGallery indexerBar;
	private TextView adText;
	// 位置的选择
    private CycledThread mSlidAdvThread;
	
	private HeadlineScrollView headlineScroll;
	private ModelResult result;
	private TabItem mTabItem;
	private AdvResult adResult;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main_indexer);
		
		ModelResult mr = WiseSiteApplication.getContext().getModelResult();
		if(mr != null){
			initUI(mr);
		} else {
			WiseSiteApplication.getContext().setOnModelReady(IndexerActivity.class.getName(), new DataSetObserver() {
				@Override
				public void onChanged() {
					ModelResult mr = WiseSiteApplication.getContext().getModelResult();
					initUI(mr);
				}
			});
		}
		
	}
	
	//初始化ui组件式样
	private void initUI(ModelResult result){
		TabItem tab = result.getTabItem(1);
		
		if(tab.indexBarList != null && tab.indexBarList.size() > 0) {
			this.result = result;
			mTabItem = result.getTabItem(1);
			headlineScroll =  (HeadlineScrollView) findViewById(R.id.headline_scroll);
			//初始化头条拉动框
			initGallery(result);
			
			//初始化快捷按键
			initShortcut(result);
			
			//设置小广告事件
			findViewById(R.id.close_adv_small).setOnClickListener(this);
			findViewById(R.id.search_input).setOnClickListener(this);
			findViewById(R.id.login_btn).setOnClickListener(this);
			ImageView logo = (ImageView) findViewById(R.id.logo_img);
			ImageLoader.getInstance().DisplayImage(new Imager(result.getLogoURI(), logo));
			
			//加载头条相关的数据
			loadHeadlineDate();
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		startAutoSlidAdv();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		stopAutoSlidAdv();
	}
	
	private int index = 0;
	private void startAutoSlidAdv()
    {
        if(smallAd != null && smallAd.getVisibility() == View.VISIBLE && mSlidAdvThread == null)
        {
            mSlidAdvThread = new CycledThread(new Runnable()
            {
                @Override
                public void run()
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                           if(adResult != null && adResult.smallAd != null && adResult.smallAd.size() > 0){
                        	   Adv adv = adResult.smallAd.get(index++);
                        	   if(adv.bitmap != null){
	                        	   smallAd.setBackgroundDrawable(adv.bitmap);
	                  			   smallAd.setTag(adv);
                        	   }
                  			   
                  			   if(index >= adResult.smallAd.size()){
                  				   index = 0;
                  			   }
                           }
                        	   
                        }
                    });
                }
            },6000);            
            mSlidAdvThread.start();
        }
    }

	private void initGallery(ModelResult result) {
		indexerBar = (IndexerBarGallery) findViewById(R.id.index_gallery);
		indexerBar.setTabId(mTabItem.id);
		IndexerBarAdapter adapter = new IndexerBarAdapter(this);
		adapter.setList(mTabItem.indexBarList);
		indexerBar.setAdapter(adapter);
		 int index = 0;
	        for (int i = 0; i < result.getTabItem(1).indexBarList.size(); i++){
	        	if(result.getTabItem(1).indexBarList.get(i).type == Constanct.HEADLIINE_ID){
	        		index = i;
	        	}
	        };
		indexerBar.setSelection(Integer.MAX_VALUE / 2 - ((Integer.MAX_VALUE / 2)  % mTabItem.indexBarList.size()) + index);
		indexerBar.setHeadline(findViewById(R.id.headline));
		indexerBar.setOther((ListView)findViewById(R.id.other_list));
	}

	private void initShortcut(ModelResult result) {
		List<ShutcutEntry>  shortcutList = mTabItem.shotcutList;
		int size = getResources().getDimensionPixelSize(R.dimen.shortcut_icon_size);
		
		TextView newInfo = (TextView) findViewById(R.id.new_info_text);
		newInfo.setText(shortcutList.get(0).title);
		findViewById(R.id.new_info).setOnClickListener(this);
		ImageLoader.getInstance().DisplayImage(new Imager(shortcutList.get(0).iconURI, (ImageView) findViewById(R.id.new_info_icon)));
		
		TextView newBuy = (TextView) findViewById(R.id.new_buy_text);
		ImageLoader.getInstance().DisplayImage(new Imager(shortcutList.get(1).iconURI, (ImageView) findViewById(R.id.new_buy_icon)));
		newBuy.setText(shortcutList.get(1).title);
		findViewById(R.id.new_buy).setOnClickListener(this);
		
		TextView newProduct = (TextView) findViewById(R.id.new_product_text);
		ImageLoader.getInstance().DisplayImage(new Imager(shortcutList.get(2).iconURI, (ImageView) findViewById(R.id.new_product_icon)));
		newProduct.setText(shortcutList.get(2).title);
		findViewById(R.id.new_product).setOnClickListener(this);
		
		TextView newShop = (TextView) findViewById(R.id.new_shop_text);
		ImageLoader.getInstance().DisplayImage(new Imager(shortcutList.get(3).iconURI, (ImageView) findViewById(R.id.new_shop_icon)));
		newShop.setText(shortcutList.get(3).title);
		findViewById(R.id.new_shop).setOnClickListener(this);
	}
	
	
    private void stopAutoSlidAdv()
    {
        if(mSlidAdvThread != null && mSlidAdvThread.isAlive())
        {
            mSlidAdvThread._stop();
            mSlidAdvThread = null;
        }
    }
	
	@SuppressWarnings("unchecked")
	public void loadHeadlineDate(){
		ViewSwitchListener switchListener = new ViewSwitchListener(){
			@Override
			public void onSwitched(View view, int position) {
				if(view != null){
					View v = view.findViewById(R.id.image);
					if(v instanceof AdvView){
						AdvView adv = (AdvView) v;
						if(adv.getData() != null && adv.getData().title != null){
							adText.setText(adv.getData().title);
						}
					}
				}
			}
			
		};
		
		OnScrollListener onScrollListener = new OnScrollListener() {
			@Override
			public void onStartScroll(View v) {
				headlineScroll.setScrollDisable(v, true);
			}
			
			@Override
			public void onScrollFinish(View v) {
				headlineScroll.setScrollDisable(null, false);
			}
		};
		
		
		
		//加载首页横条广告
		adViewFlow = (ViewFlow) findViewById(R.id.viewflow);
		smallAd = findViewById(R.id.adv_small);
		adText = (TextView)findViewById(R.id.ad_text);
        mAdvAdapter = new AdvListAdapter(this);
        adViewFlow.setAdapter(mAdvAdapter);
        CircleFlowIndicator indic = (CircleFlowIndicator) findViewById(R.id.viewflowindic);
        adViewFlow.setFlowIndicator(indic);
        final OnClickListener adClick = new OnClickListener() {
			public void onClick(View v) {
				try{
					Adv ad = (Adv) v.getTag();
					if(ad != null && ad.url != null){
						startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(ad.url)));
					}
				}catch (Exception e) {
					Log.w("ACTION_VIEW", "", e);
				}
			}
		};
		 mAdvAdapter.setAdClick(adClick);
        
        BannerAction bannerAction = new BannerAction();
        bannerAction.setActionListener(new ActionListener<AdvResult>() {
			public void onSucceed(AdvResult result) {
				AdvSuperResult r = new AdvSuperResult();
				r.advToSuper(result);
				FileCache.getInstance().put("AdvResult", r, true);
				
				if(result.list != null && result.list.size() != 0){
					mAdvAdapter.setList(result.list);
					adText.setText(result.list.get(0).title);
				}
				
				if(result.smallAd != null && result.smallAd.size() != 0){
					smallAd.setVisibility(View.VISIBLE);
					if(adResult == null){
						adResult = result;
						startAutoSlidAdv();
					}
					startAutoSlidAdv();
					smallAd.setOnClickListener(adClick);
				}
			}
			public void onError(int resultCode) {
				AdvSuperResult r = (AdvSuperResult) FileCache.getInstance().get("AdvResult");
				if(r != null){
					AdvResult advs = new AdvResult();
					advs.advToSuper(r);
					onSucceed(advs);
				}
			}
		});
        ProtocolManager.getProtocolManager().submitAction(bannerAction);
        
        adViewFlow.setOnScrollListener(onScrollListener);
        adViewFlow.setOnViewSwitchListener(switchListener);
        //end
        
        int typeId = 0;
        for (IndexerBarEntry entry : result.getTabItem(1).indexBarList){
        	if(entry.type == Constanct.HEADLIINE_ID){
        		typeId = entry.id;
        	}
        };
        
        
        //加载头条资讯
        headlineList = (ListView) findViewById(R.id.headline_list);
        headline = new InfoListAdatper(ITEM_TYPE.INFO_HEADLINE_TYPE, this);
        headline.setListView(headlineList);
        headline.setTypeId(typeId);
        headline.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				InfoItem item = (InfoItem) v.getTag();
				if(item != null){
					Intent intent = new Intent(getApplicationContext(), InfoDetailsActivity.class);
					intent.putExtra(Constanct.INFO_ENTRY, item);
					startActivity(intent);
				}
			}
		});
        headline.loadData();
        //end
        
        
        //加载头条商家
        final View right = findViewById(R.id.right_arrow);
        final View left = findViewById(R.id.left_arrow);
        shopViewFlow = (ViewFlow) findViewById(R.id.shop_flow);
        headlineShop = new InfoListAdatper(ITEM_TYPE.SHOP_HEADLINE_TYPE, this);
//        headlineShop.setType(typeId);
        headlineShop.moveToFristPage();
        headlineShop.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), ShopsDetailsActivity.class);
				ShopItem item = (ShopItem) v.getTag();
				intent.putExtra(Constanct.INFO_ENTRY, item);
				
				startActivity(intent);
			}
		});
        shopViewFlow.setAdapter(headlineShop);
        headlineShop.loadData();
        shopViewFlow.setOnScrollListener(onScrollListener);
        shopViewFlow.setOnViewSwitchListener(new ViewSwitchListener() {
			@Override
			public void onSwitched(View view, int position) {
				if(position == 0){
					right.setVisibility(View.VISIBLE);
					left.setVisibility(View.INVISIBLE);
				} else if(position == headlineShop.getCount() - 1){
					right.setVisibility(View.INVISIBLE);
					left.setVisibility(View.VISIBLE);
				} else {
					right.setVisibility(View.VISIBLE);
					left.setVisibility(View.VISIBLE);
				}
			}
		});
        //end
	}

	@Override
	public void onClick(View v) {
		switch ( v.getId()) {
		case R.id.new_buy:{
			Intent intent = new Intent("sw.buy");
			sendBroadcast(intent);
			break;
		}
		case R.id.new_info:{
//			for(IndexerBarEntry entry : mTabItem.indexBarList){
//				if(entry.type == Constanct.ALL_ID){
//					
//				}
//			}
			indexerBar.toIndex(1);
			break;
		}	
		case R.id.new_shop:{
			Intent intent = new Intent("sw.shop");
			sendBroadcast(intent);
			break;
		}	
		case R.id.new_product:{
			Intent intent = new Intent("sw.sale");
			sendBroadcast(intent);
			break;
		}
		case R.id.login_btn:{
			Intent intent = new Intent("sw.login");
			sendBroadcast(intent);
			break;
		}
		case R.id.close_adv_small:{
			findViewById(R.id.adv_small).setVisibility(View.GONE);
			stopAutoSlidAdv();
			break;
		}
		case R.id.search_input:{
			Intent intent = new Intent(getApplicationContext(), SearchActivity.class);
			startActivity(intent);
		}
		default:
			break;
		}
	}
}
